﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LineWatch.Common;
using DBAccessLib;
using System.Globalization;
using System.IO;

namespace LineWatch_WinForm
{
    public partial class ProductManagementView : Form
    {
        private const string COMMAND_HEADER = "@00RD";

        PositionManagementView positionManagementView = new PositionManagementView();
        ScreenSaver screenSaver = null;

        private UserAndLineCodeModel userAndLineCodeModel = new UserAndLineCodeModel();

        private Dictionary<string, string> serialPortsAndLineCodes = new Dictionary<string, string>();
        private Dictionary<string, SerialPortOperator> lineCodesAndSerialPortOperators
                                                       = new Dictionary<string, SerialPortOperator>();

        private SerialPortOperator serialPortOperator1 = null;

        private string planNumPositionLine1 = string.Empty;
        private string NowplanNumPositionLine1 = string.Empty;
        private string productNumPositionLine1 = string.Empty;
        private string stopTimePositionLine1 = string.Empty;
        private string CTSignalDMPositionLine1 = string.Empty;
        private string CTTimeDMPositionLine1 = string.Empty;
        private string CTTimeLine1 = string.Empty;
        private DateTime currentNowPlanUpdatedTimeLine1 = DateTime.Now;

        private PositionCommandType currentPositionCommandTypeLine1 = PositionCommandType.AllProductData;

        private ProductInfoType productInfoTypeLine1 = ProductInfoType.AllProductInfo;

        // Position Management
        private int minPositionLine1 = 0;
        private int maxPositionLine1 = 0;
        private int currentStartPositionLine1 = 0;
        private int currentEndPositionLine1 = 0;

        private Dictionary<int, string> positionStatusLine1 = new Dictionary<int, string>();

        /// <summary>
        /// Constructor
        /// </summary>
        public ProductManagementView()
        {
            InitializeComponent();

            this.timer.Enabled = false;

            string defaultValue = "0";

            this.lblDayPlanLine1.Text = defaultValue;
            this.lblCurrentPlanLine1.Text = defaultValue;
            this.lblActualCompletedLine1.Text = defaultValue;
            this.lblStopTimeLine1.Text = defaultValue;

            this.InitFont();
        }

        /// <summary>
        /// Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProductManagementView_Load(object sender, EventArgs e)
        {
            this.GetUserAndLineCode();
            this.GetAllLines();
            this.InitOperationArea();
            this.InitDMPositionAndCommandType();

            this.minPositionLine1 = ConfigInfo.GetMinPosition(ConfigInfo.LineCode1);
            this.maxPositionLine1 = ConfigInfo.GetMaxPosition(ConfigInfo.LineCode1);
            this.currentStartPositionLine1 = this.minPositionLine1;
            this.currentEndPositionLine1 = this.minPositionLine1;
        }

        /// <summary>
        /// Shown
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProductManagementView_Shown(object sender, EventArgs e)
        {
            Util.PositionNormalTime = DateTime.Now;

            if (ConfigInfo.CurrentLineCodeCount >= 1)
            {
                // Send Line1 Data
                if (productInfoTypeLine1 == ProductInfoType.AllProductInfo)
                {
                    this.currentPositionCommandTypeLine1 = PositionCommandType.AllProductData;
                    this.serialPortOperator1.WriteLine(COMMAND_HEADER + planNumPositionLine1 + "0003");
                }
                else
                {
                    this.currentPositionCommandTypeLine1 = PositionCommandType.PlanNum;
                    this.serialPortOperator1.WriteLine(COMMAND_HEADER + planNumPositionLine1 + "0001");
                }
            }

            this.timer.Enabled = true;
        }

        /// <summary>
        /// Get User And Line Code
        /// </summary>
        private void GetUserAndLineCode()
        {
            this.userAndLineCodeModel = Account.GetUserAndLineCode(LoginInfo.UserName);
            ////ConfigInfo.CurrentLineCodeCount = this.userAndLineCodeModel.UserAndLineCodeTable.Rows.Count;
        }

        /// <summary>
        /// Get All Lines
        /// </summary>
        private void GetAllLines()
        {
            ConfigInfo.DtAllLines = Product.GetAllLines();
        }

        /// <summary>
        /// Init Operation Area
        /// </summary>
        private void InitOperationArea()
        {
            string productManagement = "生产管理看板";
            if (ConfigInfo.CurrentLineCodeCount <= 0)
            {
                this.tlpMain.Visible = false;
            }

            if (ConfigInfo.CurrentLineCodeCount >= 1)
            {
                ConfigInfo.LineCode1
                    = this.userAndLineCodeModel.UserAndLineCodeTable.Rows[0]["Flow"].ToString().Trim();

                string lineName1 = ConfigInfo.GetLineNameByCode(ConfigInfo.LineCode1);

                ConfigInfo.DtLineWatchSys1 = Config.GetLineWatchSys(ConfigInfo.LineCode1);

                this.lblShiftLine1.Text = ConfigInfo.GetShiftInfo(ConfigInfo.DtLineWatchSys1);

                this.lblProductManagement1.Text = lineName1 + productManagement;

                //ConfigInfo.NowPlan = ConfigInfo.GetNowPlanInfo(ConfigInfo.DtLineWatchSys1);
                //this.lblCurrentPlanLine1.Text = ConfigInfo.NowPlan;

                string serialPortName1 = ConfigInfo.GetLineSerialPortByCode(ConfigInfo.LineCode1);
                this.serialPortsAndLineCodes.Add(serialPortName1, ConfigInfo.LineCode1);

                try
                {
                    this.serialPortOperator1 = new SerialPortOperator();
                    this.Controls.Add(this.serialPortOperator1);
                    this.serialPortOperator1.InitPort(serialPortName1, 9600);
                    this.serialPortOperator1.InterfaceUpdateHandle
                               = new InterfaceUpdateHandler(InterfaceUpdate1);

                    this.lineCodesAndSerialPortOperators.Add(ConfigInfo.LineCode1, this.serialPortOperator1);
                }
                catch
                {

                }
            }
        }

        /// <summary>
        /// Init Font
        /// </summary>
        private void InitFont()
        {
            foreach (Control control in this.Controls)
            {
                if (control.GetType() == typeof(Label))
                {
                    Label lbl = (Label)control;
                    if (lbl.Tag != null)
                    {
                        this.UpdateFont(lbl);
                    }
                }

                InitFont(control);
            }
        }

        /// <summary>
        /// Init Font
        /// </summary>
        /// <param name="controlParent"></param>
        private void InitFont(Control controlParent)
        {
            foreach (Control control in controlParent.Controls)
            {
                if (control.GetType() == typeof(Label))
                {
                    Label lbl = (Label)control;
                    if (lbl.Tag != null)
                    {
                        this.UpdateFont(lbl);
                    }
                }

                InitFont(control);
            }
        }

        /// <summary>
        /// Update Font
        /// </summary>
        /// <param name="control"></param>
        private void UpdateFont(Control control)
        {
            if (control.Tag.ToString().StartsWith("FontSizeTitle"))
            {
                this.SetFont(control, "Microsoft YaHei", ConfigInfo.ProductFontSizeTitle, FontStyle.Bold);
            }
            else if (control.Tag.ToString().StartsWith("FontSizeCaption"))
            {
                this.SetFont(control, "Microsoft YaHei", ConfigInfo.ProductFontSizeCaption, FontStyle.Bold);
            }
            else if (control.Tag.ToString().StartsWith("FontSizeValue"))
            {
                this.SetFont(control, "Microsoft YaHei", ConfigInfo.ProductFontSizeValue, FontStyle.Bold);
            }
        }

        /// <summary>
        /// Set Font
        /// </summary>
        /// <param name="control"></param>
        /// <param name="familyName"></param>
        /// <param name="emSize"></param>
        /// <param name="style"></param>
        private void SetFont(Control control, string familyName, float emSize, FontStyle style)
        {
            control.Font = new System.Drawing.Font(familyName,
                                                   emSize,
                                                   style,
                                                   System.Drawing.GraphicsUnit.Point,
                                                   ((byte)(0))
                                                   );
        }

        /// <summary>
        /// Init DM Position And Command Type
        /// </summary>
        private void InitDMPositionAndCommandType()
        {
            this.planNumPositionLine1 = ConfigurationManager.AppSettings["PlanNumDMPositionLine1"].ToString().Trim();
            this.NowplanNumPositionLine1 = ConfigurationManager.AppSettings["NowPlanNumDMPositionLine1"].ToString().Trim();
            this.productNumPositionLine1 = ConfigurationManager.AppSettings["ProductNumDMPositionLine1"].ToString().Trim();
            this.stopTimePositionLine1 = ConfigurationManager.AppSettings["StopTimeDMPositionLine1"].ToString().Trim();
            this.CTSignalDMPositionLine1 = ConfigurationManager.AppSettings["CTSignalDMPositionLine1"].ToString().Trim();
            this.CTTimeDMPositionLine1 = ConfigurationManager.AppSettings["CTTimeDMPositionLine1"].ToString().Trim();

            // Init Line1 Status
            int planNumPositionTemp = int.Parse(this.planNumPositionLine1);
            int NowplanNumPositionTemp = int.Parse(this.NowplanNumPositionLine1);
            int productNumPositionTemp = int.Parse(this.productNumPositionLine1);
            int stopTimePositionTemp = int.Parse(this.stopTimePositionLine1);

            if ((planNumPositionTemp + 1 == productNumPositionTemp)
                && (planNumPositionTemp + 2 == stopTimePositionTemp)
                && (planNumPositionTemp + 3 == NowplanNumPositionTemp))
            {
                this.currentPositionCommandTypeLine1 = PositionCommandType.AllProductData;
                this.productInfoTypeLine1 = ProductInfoType.AllProductInfo;
            }
            else
            {
                this.currentPositionCommandTypeLine1 = PositionCommandType.PlanNum;
                this.productInfoTypeLine1 = ProductInfoType.SingleProdutInfo;
            }
        }

        /// <summary>
        /// Interface Update 1
        /// </summary>
        /// <param name="text"></param>
        /// <param name="portName"></param>
        private void InterfaceUpdate1(string text, string portName)
        {
            this.ResolveDataAndSendCommand(text, portName,
                                           ref this.currentPositionCommandTypeLine1,
                                           this.productInfoTypeLine1,
                                           this.serialPortOperator1,
                                           this.planNumPositionLine1,
                                           this.NowplanNumPositionLine1,
                                           this.productNumPositionLine1,
                                           this.stopTimePositionLine1,
                                           this.CTTimeDMPositionLine1,
                                           this.CTSignalDMPositionLine1,
                                           ref this.CTTimeLine1,
                                           this.minPositionLine1,
                                           this.maxPositionLine1,
                                           ref this.currentStartPositionLine1,
                                           ref this.currentEndPositionLine1,
                                           this.positionStatusLine1
                                           );
        }

        /// <summary>
        /// Resolve Data And Send Command
        /// </summary>
        /// <param name="text"></param>
        /// <param name="portName"></param>
        /// <param name="currentPositionCommandType"></param>
        /// <param name="productInfoType"></param>
        /// <param name="serialPortOperator"></param>
        /// <param name="planNumPosition"></param>
        /// <param name="NowplanNumPosition"></param>
        /// <param name="productNumPosition"></param>
        /// <param name="stopTimePosition"></param>
        /// <param name="maxPosition"></param>
        /// <param name="currentStartPosition"></param>
        /// <param name="currentEndPosition"></param>
        /// <param name="positionStatus"></param>
        private void ResolveDataAndSendCommand(string text, string portName,
                                               ref PositionCommandType currentPositionCommandType,
                                               ProductInfoType productInfoType,
                                               SerialPortOperator serialPortOperator,
                                               string planNumPosition,
                                               string NowplanNumPosition,
                                               string productNumPosition,
                                               string stopTimePosition,
                                               string CTTimeDMPosition,
                                               string CTSignalDMPosition,
                                               ref string CTTime,
                                               int minPosition,
                                               int maxPosition,
                                               ref int currentStartPosition,
                                               ref int currentEndPosition,
                                               Dictionary<int, string> positionStatus)
        {
            NeedToCloseApp();
            if (currentPositionCommandType == PositionCommandType.AllProductData)
            {
                int planNumGroupIndex = 1;
                int productNumGroupIndex = 2;
                int stopTimeGroupIndex = 3;
                int NowplanNumGroupIndex = 4;

                string planNum = this.GetProductDataByGroup(text, planNumGroupIndex);
                string productNum = this.GetProductDataByGroup(text, productNumGroupIndex);
                string stopTime = this.GetProductDataByGroup(text, stopTimeGroupIndex);
                string NowplanNum = this.GetProductDataByGroup(text, NowplanNumGroupIndex);

                this.UpdateUI(planNum,NowplanNum, productNum, stopTime, portName);

                currentPositionCommandType = PositionCommandType.CTTime;
                serialPortOperator.WriteLine(COMMAND_HEADER + CTTimeDMPosition + "0001");


                ////currentPositionCommandType = PositionCommandType.PositionSHA;
                ////serialPortOperator.WriteLine(COMMAND_HEADER
                ////                             + currentStartPosition.ToString("0000")
                ////                             + ConfigInfo.PositionNumInOneCommand.ToString("0000"));

                ////currentEndPosition = currentStartPosition + ConfigInfo.PositionNumInOneCommand - 1;
            }
            else if (currentPositionCommandType == PositionCommandType.PlanNum)
            {
                int planNumGroupIndex = 1;

                string planNum = this.GetProductDataByGroup(text, planNumGroupIndex);
                string NowplanNum = string.Empty;
                string productNum = string.Empty;
                string stopTime = string.Empty;

                this.UpdateUI(planNum, NowplanNum, productNum, stopTime, portName);

                currentPositionCommandType = PositionCommandType.ProductNum;
                serialPortOperator.WriteLine(COMMAND_HEADER + productNumPosition + "0001");
            }
            else if (currentPositionCommandType == PositionCommandType.ProductNum)
            {
                int productNumGroupIndex = 1;

                string planNum = string.Empty;
                string NowplanNum = string.Empty;
                string productNum = this.GetProductDataByGroup(text, productNumGroupIndex);
                string stopTime = string.Empty;

                this.UpdateUI(planNum, NowplanNum, productNum, stopTime, portName);

                currentPositionCommandType = PositionCommandType.StopTime;
                serialPortOperator.WriteLine(COMMAND_HEADER + stopTimePosition + "0001");
            }
            else if (currentPositionCommandType == PositionCommandType.StopTime)
            {
                int stopTimeGroupIndex = 1;

                string planNum = string.Empty;
                string NowplanNum = string.Empty;
                string productNum = string.Empty;
                string stopTime = this.GetProductDataByGroup(text, stopTimeGroupIndex);

                this.UpdateUI(planNum, NowplanNum, productNum, stopTime, portName);

                currentPositionCommandType = PositionCommandType.NowPlanNum;
                serialPortOperator.WriteLine(COMMAND_HEADER + NowplanNumPosition + "0001");


                ////currentPositionCommandType = PositionCommandType.PositionSHA;

                ////serialPortOperator.WriteLine(COMMAND_HEADER
                ////                             + currentStartPosition.ToString("0000")
                ////                             + ConfigInfo.PositionNumInOneCommand.ToString("0000"));

                ////currentEndPosition = currentStartPosition + ConfigInfo.PositionNumInOneCommand - 1;
            }
            else if (currentPositionCommandType == PositionCommandType.NowPlanNum)
            {
                int NowplanNumGroupIndex = 1;

                string planNum = string.Empty;
                string NowplanNum = this.GetProductDataByGroup(text, NowplanNumGroupIndex);
                string productNum = string.Empty;
                string stopTime = string.Empty;

                this.UpdateUI(planNum, NowplanNum, productNum, stopTime, portName);

                currentPositionCommandType = PositionCommandType.CTTime;
                serialPortOperator.WriteLine(COMMAND_HEADER + CTTimeDMPosition + "0001");
            }
            else if (currentPositionCommandType == PositionCommandType.CTTime)
            {
                int groupIndex = 1;

                CTTime = this.GetProductDataByGroup(text, groupIndex);

                currentPositionCommandType = PositionCommandType.CTSignal;
                serialPortOperator.WriteLine(COMMAND_HEADER + CTSignalDMPosition + "0001");
            }
            else if (currentPositionCommandType == PositionCommandType.CTSignal)
            {
                int groupIndex = 1;

                string CTSignal = this.GetProductDataByGroup(text, groupIndex);

                this.UpdateNowPlanUI(CTTime, CTSignal, portName);

                ////currentPositionCommandType = PositionCommandType.PositionSHA;

                ////serialPortOperator.WriteLine(COMMAND_HEADER
                ////                             + currentStartPosition.ToString("0000")
                ////                             + ConfigInfo.PositionNumInOneCommand.ToString("0000"));

                ////currentEndPosition = currentStartPosition + ConfigInfo.PositionNumInOneCommand - 1;

                currentPositionCommandType = PositionCommandType.PlanNumSetting;

                if (!string.IsNullOrWhiteSpace(ConfigInfo.PlanNumSettingCommand))
                {
                    serialPortOperator.WriteLine(ConfigInfo.PlanNumSettingCommand);
                    ConfigInfo.PlanNumSettingCommand = string.Empty;
                }
                else
                {
                    serialPortOperator.WriteLine(COMMAND_HEADER + CTSignalDMPosition + "0001");
                }
            }
            else if (currentPositionCommandType == PositionCommandType.PlanNumSetting)
            {
                currentPositionCommandType = PositionCommandType.CTTimeSetting;

                if (!string.IsNullOrWhiteSpace(ConfigInfo.CTTimeSettingCommand))
                {
                    serialPortOperator.WriteLine(ConfigInfo.CTTimeSettingCommand);
                    ConfigInfo.CTTimeSettingCommand = string.Empty;
                }
                else
                {
                    serialPortOperator.WriteLine(COMMAND_HEADER + CTSignalDMPosition + "0001");
                }
            }
            else if (currentPositionCommandType == PositionCommandType.CTTimeSetting)
            {
                currentPositionCommandType = PositionCommandType.PlanNumReset;

                if (!string.IsNullOrWhiteSpace(ConfigInfo.PlanNumResetCommand))
                {
                    serialPortOperator.WriteLine(ConfigInfo.PlanNumResetCommand);
                    ConfigInfo.PlanNumResetCommand = string.Empty;
                }
                else
                {
                    serialPortOperator.WriteLine(COMMAND_HEADER + CTSignalDMPosition + "0001");
                }
            }
            else if (currentPositionCommandType == PositionCommandType.PlanNumReset)
            {
                currentPositionCommandType = PositionCommandType.NowPlanNumReset;

                if (!string.IsNullOrWhiteSpace(ConfigInfo.NowPlanNumResetCommand))
                {
                    serialPortOperator.WriteLine(ConfigInfo.NowPlanNumResetCommand);
                    ConfigInfo.NowPlanNumResetCommand = string.Empty;
                }
                else
                {
                    serialPortOperator.WriteLine(COMMAND_HEADER + CTSignalDMPosition + "0001");
                }
            }
            else if (currentPositionCommandType == PositionCommandType.NowPlanNumReset)
            {
                currentPositionCommandType = PositionCommandType.ProductNumReset;

                if (!string.IsNullOrWhiteSpace(ConfigInfo.ProductNumResetCommand))
                {
                    serialPortOperator.WriteLine(ConfigInfo.ProductNumResetCommand);
                    ConfigInfo.ProductNumResetCommand = string.Empty;
                }
                else
                {
                    serialPortOperator.WriteLine(COMMAND_HEADER + CTSignalDMPosition + "0001");
                }
            }
            else if (currentPositionCommandType == PositionCommandType.ProductNumReset)
            {
                currentPositionCommandType = PositionCommandType.StopTimeReset;

                if (!string.IsNullOrWhiteSpace(ConfigInfo.StopTimeResetCommand))
                {
                    serialPortOperator.WriteLine(ConfigInfo.StopTimeResetCommand);
                    ConfigInfo.StopTimeResetCommand = string.Empty;
                }
                else
                {
                    serialPortOperator.WriteLine(COMMAND_HEADER + CTSignalDMPosition + "0001");
                }
            }
            else if (currentPositionCommandType == PositionCommandType.StopTimeReset)
            {
                currentPositionCommandType = PositionCommandType.PositionSHA;

                serialPortOperator.WriteLine(COMMAND_HEADER
                                             + currentStartPosition.ToString("0000")
                                             + ConfigInfo.PositionNumInOneCommand.ToString("0000"));

                currentEndPosition = currentStartPosition + ConfigInfo.PositionNumInOneCommand - 1;
            }
            else if (currentPositionCommandType == PositionCommandType.PositionSHA)
            {
                this.GetPositionStatus(text, currentStartPosition, currentEndPosition, positionStatus);

                // Update Position Management Form
                this.UpdatePositionUI(positionStatus, portName);

                if (currentEndPosition >= maxPosition)
                {
                    currentEndPosition = minPosition;
                    currentStartPosition = minPosition;
                    if (productInfoType == ProductInfoType.AllProductInfo)
                    {
                        currentPositionCommandType = PositionCommandType.AllProductData;
                        serialPortOperator.WriteLine(COMMAND_HEADER + planNumPosition + "0003");
                    }
                    else
                    {
                        currentPositionCommandType = PositionCommandType.PlanNum;
                        serialPortOperator.WriteLine(COMMAND_HEADER + planNumPosition + "0001");
                    }
                }
                else
                {
                    currentStartPosition = currentEndPosition + 1;
                    currentPositionCommandType = PositionCommandType.PositionSHA;
                    serialPortOperator.WriteLine(COMMAND_HEADER
                                                 + currentStartPosition.ToString("0000")
                                                 + ConfigInfo.PositionNumInOneCommand.ToString("0000"));

                    currentEndPosition = currentStartPosition + ConfigInfo.PositionNumInOneCommand - 1;
                }
            }
        }

        private void NeedToCloseApp()
        {
            if (this.positionManagementView != null)
            {
                if (this.positionManagementView.isClosedApp)
                {
                    this.btnQuit_Click(null, EventArgs.Empty);
                }
            }
        }

        /// <summary>
        /// Update UI
        /// </summary>
        /// <param name="text"></param>
        /// <param name="portName"></param>
        private void UpdateUI(string planNum, string NowplanNum, string productNum, string stopTime, string portName)
        {
            long planNumber = -1;
            long NowplanNumber = -1;
            long productNumber = -1;
            long stopTimeNumber = -1;
            long temp = 0;

            if (long.TryParse(planNum, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out temp))
            {
                long.TryParse(planNum, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out planNumber);
            }

            if (long.TryParse(NowplanNum, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out temp))
            {
                long.TryParse(NowplanNum, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out NowplanNumber);
            }

            if (long.TryParse(productNum, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out temp))
            {
                long.TryParse(productNum, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out productNumber);
            }

            if (long.TryParse(stopTime, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out temp))
            {
                long.TryParse(stopTime, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out stopTimeNumber);
            }

            string lineCode = this.serialPortsAndLineCodes[portName];
            this.UpdateProductInfo(planNumber,NowplanNumber, productNumber, (stopTimeNumber == -1 ? -1 : (stopTimeNumber / 60)), lineCode);
        }

        /// <summary>
        /// Update Product Info
        /// </summary>
        /// <param name="lineCode"></param>
        /// <param name="planNum"></param>
        /// <param name="productNum"></param>
        /// <param name="stopTime"></param>
        private void UpdateProductInfo(long planNum, long NowplanNum, long productNum, long stopTime, string lineCode)
        {
            if (string.Equals(ConfigInfo.LineCode1, lineCode))
            {
                if (planNum >= 0)
                {
                    this.lblDayPlanLine1.Text = planNum.ToString();
                    ////this.lblCurrentPlanLine1.Text
                    ////    = ConfigInfo.GetNowPlanInfo(ConfigInfo.DtLineWatchSys1, planNum);
                }

                if (NowplanNum >= 0)
                {
                    this.lblCurrentPlanLine1.Text = NowplanNum.ToString();
                    ConfigInfo.NowPlan = NowplanNum.ToString();
                    ////this.lblCurrentPlanLine1.Text
                    ////    = ConfigInfo.GetNowPlanInfo(ConfigInfo.DtLineWatchSys1, planNum);
                }

                if (productNum >= 0)
                {
                    this.lblActualCompletedLine1.Text = productNum.ToString();
                    ConfigInfo.ActualCompleted = productNum.ToString();
                }

                if (stopTime >= 0)
                {
                    this.lblStopTimeLine1.Text = stopTime.ToString();
                    ConfigInfo.StopTime = stopTime.ToString();
                }
            }

            this.Refresh();
            this.Update();
        }

        /// <summary>
        /// Update Now Plan UI
        /// </summary>
        /// <param name="CTTime"></param>
        /// <param name="CTSignal"></param>
        /// <param name="portName"></param>
        private void UpdateNowPlanUI(string CTTime, string CTSignal, string portName)
        {
            long CTTimeNumber = -1;
            long CTSignalNumber = -1;

            long temp = 0;

            if (long.TryParse(CTTime, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out temp))
            {
                long.TryParse(CTTime, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out CTTimeNumber);
            }

            if (long.TryParse(CTSignal, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out temp))
            {
                long.TryParse(CTSignal, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out CTSignalNumber);
            }

            string lineCode = this.serialPortsAndLineCodes[portName];
            this.UpdateNowPlanInfo(CTTimeNumber, CTSignalNumber, lineCode);
        }

        /// <summary>
        /// Update Now Plan Info
        /// </summary>
        /// <param name="CTTime"></param>
        /// <param name="CTSignal"></param>
        /// <param name="lineCode"></param>
        private void UpdateNowPlanInfo(long CTTime, long CTSignal, string lineCode)
        {
            if (CTSignal == 1)
            {
                if (string.Equals(ConfigInfo.LineCode1, lineCode))
                {
                    if ((DateTime.Now - this.currentNowPlanUpdatedTimeLine1).TotalSeconds >= CTTime)
                    {
                        string nowPlanTemp = this.lblCurrentPlanLine1.Text.Trim();
                        long nowPlan = 0;

                        long.TryParse(nowPlanTemp, out nowPlan);
                        nowPlan++;

                        this.lblCurrentPlanLine1.Text = nowPlan.ToString();
                        ConfigInfo.NowPlan = nowPlan.ToString();
                        ConfigInfo.NowPlanNumResetCommand = "@00WD" + ConfigurationManager.AppSettings["NowPlanNumDMPositionLine1"].ToString().Trim() + nowPlan.ToString("X").PadLeft(4, '0');
                        //serialPortOperator1.WriteLine(COMMAND_HEADER + ConfigurationManager.AppSettings["NowPlanNumDMPositionLine1"].ToString().Trim() + nowPlan.ToString("X").PadLeft(4, '0'));
                        this.currentNowPlanUpdatedTimeLine1 = DateTime.Now;
                    }
                }

                this.Refresh();
                this.Update();
            }
        }

        /// <summary>
        /// Get Product Data By Group
        /// </summary>
        /// <param name="text"></param>
        /// <param name="groupIndex"></param>
        /// <returns></returns>
        private string GetProductDataByGroup(string text, int groupIndex)
        {
            if (groupIndex == 1)
            {
                return text.Substring(0, 4);
            }

            if (groupIndex == 2) return text.Substring(4, 4);

            if (groupIndex == 3)
            {
                return text.Substring(8, 4);
            }

            if (groupIndex == 4)
            {
                return text.Substring(12, 4);
            }

            return string.Empty;
        }

        /// <summary>
        /// Update Position UI
        /// </summary>
        /// <param name="positionStatus"></param>
        /// <param name="portName"></param>
        private void UpdatePositionUI(Dictionary<int, string> positionStatus, string portName)
        {
            if (this.positionManagementView == null)
            {
                this.positionManagementView = new PositionManagementView();
            }

            this.positionManagementView.isClosedApp = false;

            string lineCode = this.serialPortsAndLineCodes[portName];
            this.positionManagementView.UpdatePositionInfo(positionStatus, lineCode);

            if (this.positionManagementView.HasSHAPosition())
            {
                if (this.screenSaver != null)
                {
                    this.screenSaver.Close();
                }

                Util.PositionNormalTime = DateTime.MaxValue;

                if (this.positionManagementView == null)
                {
                    this.positionManagementView = new PositionManagementView();
                }

                if (this.positionManagementView.IsDisposed)
                {
                    this.positionManagementView = new PositionManagementView();
                }

                this.positionManagementView.Show();
                this.positionManagementView.BringToFront();
                this.positionManagementView.Focus();
            }
            else
            {
                if (Util.PositionNormalTime == DateTime.MaxValue)
                {
                    Util.PositionNormalTime = DateTime.Now;
                }

                this.positionManagementView.Hide();
            }
        }

        /// <summary>
        /// Get Position Status
        /// </summary>
        /// <param name="text"></param>
        /// <param name="currentStartPosition"></param>
        /// <param name="currentEndPosition"></param>
        /// <param name="positionStatus"></param>
        private void GetPositionStatus(string status,
                                       int currentStartPosition,
                                       int currentEndPosition,
                                       Dictionary<int, string> positionStatus)
        {
            for (int position = currentStartPosition; position <= currentEndPosition; position++)
            {
                if (status.Length >= 4)
                {
                    if (!positionStatus.ContainsKey(position))
                    {
                        positionStatus.Add(position, status.Substring(0, 4));
                    }
                    else
                    {
                        positionStatus[position] = status.Substring(0, 4);
                    }

                    if (status.Length > 4)
                    {
                        status = status.Substring(4, status.Length - 4);
                    }
                    else
                    {
                        status = string.Empty;
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// Change Shift Name and Update Product Log
        /// </summary>
        /// <returns></returns>
        private bool ChangeShiftNameAndUpdateProductLog()
        {
            bool isShiftNameChanged = false;

            string shiftInfoLine1 = string.Empty;

            if (ConfigInfo.CurrentLineCodeCount >= 1)
            {
                shiftInfoLine1 = ConfigInfo.GetShiftInfo(ConfigInfo.DtLineWatchSys1);

                if (!string.Equals(this.lblShiftLine1.Text.Trim(), shiftInfoLine1.Trim()))
                {
                    isShiftNameChanged = true;
                    //this.lblCurrentPlanLine1.Text = "0";
                    //ConfigInfo.NowPlan = "0";
                    this.currentNowPlanUpdatedTimeLine1 = DateTime.Now;
                }
            }

            if (isShiftNameChanged)
            {
                this.UpdateProductLog();

                this.lblShiftLine1.Text = shiftInfoLine1.Trim();
            }

            return isShiftNameChanged;
        }

        /// <summary>
        /// Get Shift
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private string GetShift(string text)
        {
            if (text.Contains("1"))
            {
                return "1";
            }
            else if (text.Contains("2"))
            {
                return "2";
            }

            return "0";
        }

        /// <summary>
        /// Update Product Log
        /// </summary>
        private void UpdateProductLog()
        {
            string logDate = DateTime.Now.Date.ToString("yyyy-MM-dd");

            if (ConfigInfo.CurrentLineCodeCount >= 1)
            {
                string shift = this.GetShift(this.lblShiftLine1.Text);
                Product.UpdateProductLogByKey(ConfigInfo.LineCode1,
                                              shift,
                                              logDate,
                                              this.lblDayPlanLine1.Text,
                                              this.lblCurrentPlanLine1.Text,
                                              this.lblActualCompletedLine1.Text,
                                              this.lblStopTimeLine1.Text);
            }
        }

        /// <summary>
        /// Show Screen Saver
        /// </summary>
        private void ShowScreenSaver()
        {
            if (this.screenSaver == null)
            {
                this.screenSaver = new ScreenSaver();
            }

            if (this.screenSaver.IsDisposed)
            {
                this.screenSaver = new ScreenSaver();
            }

            if (!this.screenSaver.Visible)
            {
                this.screenSaver.ShowDialog();
            }
        }

        /// <summary>
        /// timer Tick
        /// for Screen Saver
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer_Tick(object sender, EventArgs e)
        {
            this.ChangeShiftNameAndUpdateProductLog();

            int timeSpan = ConfigInfo.GetScreenTimeSpan1(ConfigInfo.DtLineWatchSys1);

            if (timeSpan <= 0)
            {
                return;
            }

            TimeSpan span = DateTime.Now - Util.PositionNormalTime;

            if (span.TotalSeconds >= timeSpan)
            {
                this.ShowScreenSaver();
            }
        }

        /// <summary>
        /// Qiut
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuit_Click(object sender, EventArgs e)
        {
            try
            {
                this.timer.Enabled = false;
                this.LabQuit.Visible = true;
                foreach (SerialPortOperator serialPortOperator in this.lineCodesAndSerialPortOperators.Values)
                {
                    serialPortOperator.ClosePort();
                }
            }
            catch
            {

            }

            try
            {
                if (this.positionManagementView == null)
                {
                    this.positionManagementView.Close();
                }
            }
            catch
            {

            }
            this.Close();

            Application.Exit();
        }

        /// <summary>
        /// Form Closing
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProductManagementView_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                ConfigInfo.SaveNowPlanValue();
                this.UpdateProductLog();
            }
            catch
            {

            }

            try
            {
                foreach (SerialPortOperator serialPortOperator in this.lineCodesAndSerialPortOperators.Values)
                {
                    serialPortOperator.ClosePort();
                }
            }
            catch
            {

            }
        }
        
        private void btnSeBeiGuZhang_Click(object sender, EventArgs e)
        {
            SeBeiGuZhangView form = new SeBeiGuZhangView();
            form.ShowDialog();
        }

        private void btnPinZhiBuLiang_Click(object sender, EventArgs e)
        {
            PinZhiBuLiangView form = new PinZhiBuLiangView();
            form.ShowDialog();
        }

        private void btnBuPinQianPin_Click(object sender, EventArgs e)
        {
            BuPinQianPinView form = new BuPinQianPinView();
            form.ShowDialog();
        }

        private void btnSetting_Click(object sender, EventArgs e)
        {
            Setup form = new Setup();
            form.ShowDialog();
        }
    }
}
